//
//  IntersectionLocationEditMapViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Ding on 10/1/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "IntersectionLocationEditMapViewController.h"

@interface IntersectionLocationEditMapViewController ()

@end

@implementation IntersectionLocationEditMapViewController
@synthesize mapView;
@synthesize intersection=_intersection;
@synthesize agency=_agency;
@synthesize subSystem=_subSystem;
//@synthesize timingPattern=_timingPattern;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setToolbarHidden:NO];
    UIBarButtonItem *buttonItem = [[ UIBarButtonItem alloc ] initWithTitle: @"Done"
                                                                     style: UIBarButtonItemStyleBordered
                                                                    target: self
                                                                    action: @selector( goBack:) ];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    self.toolbarItems = [ NSArray arrayWithObjects:homeButtonItem,space, buttonItem,nil];
    [ buttonItem release ];
    
    
    self.mapView.delegate = self;
    locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    
    MKCoordinateRegion region;
    //    = MKCoordinateRegionMakeWithDistance(self.signal.coordinate ,5000,5000);
//    Intersection *intersection=[XMLParser getIntersection:self.signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    if (self.intersection.intersectionCoordinate.latitude!=0) {
        region = MKCoordinateRegionMakeWithDistance(self.intersection.intersectionCoordinate ,5000,5000);
    }else {
        region=[PropertyReadingWritingClass readMapRegionFromPropertyFile];
    }
    //    MKCoordinateRegion region=[PropertyReadingWritingClass readMapRegionFromPropertyFile];
    if (region.center.latitude==0) {
        region = MKCoordinateRegionMakeWithDistance(locationManager.location.coordinate ,5000,5000);
    }
    [self.mapView setRegion:region animated:YES];
    [self.mapView setShowsUserLocation:NO];
    
    CLLocationCoordinate2D newCoord = region.center;
    MapPoint *mp = [[[MapPoint alloc] initWithCoordinate:newCoord title:self.intersection.intersectionName subTitle:@"Edit Location"] autorelease];
    [self.mapView addAnnotation:mp];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [self setMapView:nil];
    [super viewDidUnload];
    self.intersection=nil;
    self.agency=nil;
    self.subSystem=nil;
//    self.timingPattern=nil;
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [PropertyReadingWritingClass writeMapRegionToPropertyFile:mapView.region];
    [XMLParser updateIntersection:self.intersection agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) goBack:(id)sender
{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc {
    [mapView release];
    [_agency release];
    [_subSystem release];
//    [_timingPattern release];
    [_intersection release];
    [super dealloc];
}

- (void)mapView:(MKMapView *)theMapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    //    [theMapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    //    CLLocationCoordinate2D userCoordinate = userLocation.location.coordinate;
    //    for(int i = 1; i<=5;i++)
    //    {
    //        CGFloat latDelta = rand()*.035/RAND_MAX -.02;
    //        CGFloat longDelta = rand()*.03/RAND_MAX -.015;
    //        CLLocationCoordinate2D newCoord = { userCoordinate.latitude + latDelta, userCoordinate.longitude + longDelta };
    //        MapPoint *mp = [[MapPoint alloc] initWithCoordinate:newCoord title:[NSString stringWithFormat:@"Azam Home %d",i] subTitle:@"Home Sweet Home"];
    //        [theMapView addAnnotation:mp];
    //        [mp release];
    //
    //    }
    
}

- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views
{
    CGRect visibleRect = [mapView annotationVisibleRect];
    
    for(MKAnnotationView *view in views)
    {
        if([view isKindOfClass:[SignalAnnotationView class]])
        {
            CGRect endFrame = view.frame;
            CGRect startFrame = endFrame;
            startFrame.origin.y = visibleRect.origin.y - startFrame.size.height;
            view.frame = startFrame;
            //            [UIView beginAnimations:@"drop" context:NULL];
            //            [UIView setAnimationDuration:2];
            view.frame = endFrame;
            [UIView commitAnimations];
        }
    }
    //    MKAnnotationView *annotationView = [views objectAtIndex:0];
    //    id<MKAnnotation> mp = [annotationView annotation];
    //    MKCoordinateRegion region;
    ////    = MKCoordinateRegionMakeWithDistance(self.signal.coordinate ,5000,5000);
    //    if (self.signal.coordinate.latitude!=0) {
    //        region = MKCoordinateRegionMakeWithDistance(self.signal.coordinate ,5000,5000);
    //    }else {
    //        region=[PropertyReadingWritingClass readMapRegionFromPropertyFile];
    //    }
    ////    MKCoordinateRegion region=[PropertyReadingWritingClass readMapRegionFromPropertyFile];
    //    if (region.center.latitude==0) {
    //        region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,5000,5000);
    //    }
    //    [mv setRegion:region animated:YES];
    
}

- (MKAnnotationView *)mapView:(MKMapView *)mv viewForAnnotation:(id <MKAnnotation>)annotation
{
    //    return nil;
    if([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    NSString *annotationIdentifier = @"SignalViewAnnotation";
    SignalAnnotationView *pinView = (SignalAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
    if (!pinView)
    {
        pinView = [[[SignalAnnotationView alloc]                     initWithAnnotation:annotation
                                                                        reuseIdentifier:annotationIdentifier] autorelease];
        
        //        [pinView setPinColor:MKPinAnnotationColorGreen];
        //        pinView.animatesDrop = YES;
        pinView.canShowCallout = NO;
        UIImageView *houseIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"green_signal.png"]];
        [houseIconView setFrame:CGRectMake(0, 0, 15, 30)];
        pinView.leftCalloutAccessoryView = houseIconView;
        pinView.rightCalloutAccessoryView=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        [houseIconView release];
    }
    else
    {
        pinView.annotation = annotation;
    }
    pinView.draggable=YES;
    return pinView;
}

- (void)mapView:(MKMapView *)mapView
 annotationView:(MKAnnotationView *)annotationView
didChangeDragState:(MKAnnotationViewDragState)newState
   fromOldState:(MKAnnotationViewDragState)oldState
{
    if (newState == MKAnnotationViewDragStateEnding)
    {
        CLLocationCoordinate2D droppedAt = annotationView.annotation.coordinate;
        NSLog(@"dropped at %f,%f", droppedAt.latitude, droppedAt.longitude);
        
        self.intersection.intersectionCoordinate=droppedAt;
        [XMLParser updateIntersection:self.intersection agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    }
}




- (id)initWithNibNameAndSignal:(NSString *)nibNameOrNil intersection:(Intersection*)intersection agency:(Agency*)agency subSystem:(SubSystem*)subSystem bundle:(NSBundle *)nibBundleOrNil
{
    self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    self.intersection=intersection;
    self.agency=agency;
    self.subSystem=subSystem;
//    self.timingPattern=timingPattern;
    
    return self;
}
- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
@end
